package spindles.gwt.server.util;

import java.security.Principal;
import java.util.NoSuchElementException;

import org.securityfilter.realm.SecurityRealmInterface;

import spindles.api.db.DBGateway;
import spindles.api.domain.Role;
import spindles.api.domain.User;
import spindles.api.util.Util;

public class BerkeleyDBSecurityRealm implements SecurityRealmInterface {
	
	private DBGateway db = new DBGateway(); 

	public Principal authenticate(String username, String password) {
		if(Util.isEmpty(username) || Util.isEmpty(password)){
			return null;
		}
		try {
			User user = db.getUser(username);
			if(user.getPassword().equalsIgnoreCase(password)){
				return new SimplePrincipal(user);
			}			
		} catch (NoSuchElementException e) {
			// username doesn`t exist
			return null;
		}
		
		//passwords are not the same
		return null;
		
	}

	public boolean isUserInRole(Principal principal, String rolename) {
		if(principal == null || Util.isEmpty(rolename) || 
				!(principal instanceof SimplePrincipal)){
			return false;
		}
		
		Role role = ((SimplePrincipal)principal).getUser().getRole();
		if (role.getName().equalsIgnoreCase(rolename)){
			return true;
		}		
		return false;
	}

}
